/**
 * 
 */
package trungsi.gea.photos.controller;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;

/**
 * @author trungsi
 *
 */
@UrlBinding("/security")
public class SecurityActionBean extends BaseActionBean {

	//@SpringBean
	private UserService userService = UserServiceFactory.getUserService();
	
	@Before
	public Resolution checkSecurity() {
		if (getContext().getEventName().equals("check")) {
			return null;
		}
		
		if (userNotLogged()) {
			return new StreamingResolution("application/json", "{succes : false, error : 'access denied'}");
		}
		
		return null;
	}
	
	private boolean userNotLogged() {
		//Principal userPrincipal = getContext().getRequest().getUserPrincipal();
		//return !(userService.isUserLoggedIn() && userService.isUserAdmin());
		return false;
	}
	
	@HandlesEvent("check")
	public Resolution check() {
		if (userNotLogged()) {
			return new StreamingResolution("application/json", "{success : false, login : '" + userService.createLoginURL("/") + "'}");
		} else {
			return new StreamingResolution("application/json", "{success : true, user : '" + getContext().getRequest().getUserPrincipal().getName() + "', logout : '" + userService.createLogoutURL("/") + "'}");
		}
	}
}
